﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using eTerm.MsSql.DbProvider;

namespace eTerm.Platform.Web.Order
{
    public partial class RequireHistory : BasePage
    {
        protected override string PageCode
        {
            get
            {
                return @"REQUIREHISTORY";
            }
        }


        protected void btnQuery_Click(object sender, EventArgs e) {
            AspNetPager1.CurrentPageIndex = 1;
            QueryData();
        }

        /// <summary>
        /// 页面初始化.
        /// </summary>
        protected override void InitPageLoad()
        {
            dlUploader.Items.Add(new ListItem() { Value=string.Empty,Text=@"[全部]" });
            SysUser.All().Join(SysCompany.All(), l => l.CompanyCode, r => r.CompanyCode, (l, r) => new { l.UserId,l.DisplayName,r.CompayName }).ToList().ForEach(l => {
                dlUploader.Items.Add(new ListItem() { Text = string.Format(@"[{0}]{1}",l.CompayName,l.DisplayName),Value = l.UserId.ToString() });
            });

            Enum.GetValues(typeof(PNRRequireStatus)).Cast<PNRRequireStatus>().ToList().ForEach(l => {
                if (GetAttribute((DetrStatus)l, typeof(QueryAttribute)) != null)
                    chkStatus.Items.Add(new ListItem(GetDescription(l), ((int)l).ToString()) { Selected = true });
            });
            ViewState["Approve"] = SysUserAuthority.All().Any(l => l.AuthorityCode == @"APPROVEREQUIRE" && l.UserId == UID);
            QueryData();
        }

        private void QueryData() {
            var sql = PnrRequire.All().Join(SysUser.All(), l => l.UserId, r => r.UserId, (l, r) => new { l.Id, l.PnrCode, RecordDate = l.RecordDate.ToString(@"yyyy-MM-dd HH:mm"),l.Description,l.RequireCode, l.StatusId, r.UserId, r.UserNo, r.CompanyCode, r.DisplayName, r.Email, RequireId = l.Id })
                .Join(SysCompany.All(), l => l.CompanyCode, r => r.CompanyCode, (l, r) => new { l.CompanyCode, l.DisplayName, l.Email, l.Id, l.PnrCode, l.RecordDate, l.RequireId,l.Description,l.RequireCode, l.StatusId, l.UserId, l.UserNo, r.CompayName })
                //.SelectMany(r => PnrPassenger.All().GroupBy(l => l.RequireId, (Key, Items) => new { Key, Names = string.Join(",", Items.Select(y => y.PassengerName).ToList()) }))

                //.SelectMany(r=>PnrPassenger.All().Where(l=>l.RequireId == r.RequireId).DefaultIfEmpty(),(l,r)=>new { l.CompanyCode,l.DisplayName,l.Email,l.Id,l.PnrCode,l.RecordDate,l.RequireId,l.StatusId,l.UserId,l.UserNo,r.PassengerName,r.IdentityNo })
                ;

            if (!string.IsNullOrEmpty(dlUploader.SelectedValue))
                sql = sql.Where(l => l.UserId == int.Parse(dlUploader.SelectedValue));

            if (!string.IsNullOrEmpty(tbRequireCode.Text.Trim()))
                sql = sql.Where(l => l.RequireCode.Contains(tbRequireCode.Text.Trim()));

            this.AspNetPager1.RecordCount = sql.Count();
            this.rptPnrRequire.DataSource = sql.Skip((AspNetPager1.CurrentPageIndex - 1) * AspNetPager1.PageSize).Take(AspNetPager1.PageSize).OrderByDescending(l => l.RecordDate);


            this.AspNetPager1.CustomInfoHTML = string.Format("当前第{0}/{1}页 共{2}条记录 每页{3}条", new object[] { this.AspNetPager1.CurrentPageIndex, this.AspNetPager1.PageCount, this.AspNetPager1.RecordCount, this.AspNetPager1.PageSize });

            this.rptPnrRequire.DataBind();
            this.AspNetPager1.DataBind();
        }

        protected void AspNetPager1_PageChanging(object sender, Wuqi.Webdiyer.PageChangingEventArgs e) {
            AspNetPager1.CurrentPageIndex = e.NewPageIndex;
            QueryData();
        }

        protected void rptPnrRequire_OnItemDataBound(object sender, RepeaterItemEventArgs e) {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) {
                LinkButton lnkHistory = e.Item.FindControl(@"lnkHistory") as LinkButton;
                LinkButton lnkUpdate = e.Item.FindControl(@"lnkUpdate") as LinkButton;
                LinkButton lnkCancel = e.Item.FindControl(@"lnkCancel") as LinkButton;

                LinkButton lnkApprove = e.Item.FindControl(@"lnkApprove") as LinkButton;


                var model = e.Item.DataItem ;
                string result = (Get<object>(model, @"Description")??string.Empty).ToString().Replace("\r", @"<br />").Replace("\n", @"<br />");
                int UserId = (int)Get<object>(model, @"UserId");
                PNRRequireStatus StatusId = (PNRRequireStatus)Get<object>(model, "StatusId");



                long Id = (long)Get<object>(model, "Id");
                lnkUpdate.OnClientClick = string.Format(@"javascript:$.jBox(""iframe:EditOrder.aspx?ID={0}"", {{
    title: ""行程及旅客信息"",
    width: 920,
    height:450,
    bottomText:'修改行程及旅客信息',
    buttons: {{ '关闭':true }}
}});return false;", Id, btnQuery.ClientID);

                lnkApprove.Visible = ((StatusId & PNRRequireStatus.PENDDING) != 0) && (bool)ViewState["Approve"];
                lnkCancel.Visible = (UID == UserId || (bool)ViewState["Approve"]) && (StatusId & (PNRRequireStatus.CANCELD)) == 0;
                lnkHistory.Visible = (StatusId & (PNRRequireStatus.ERROR | PNRRequireStatus.SUCCESS)) != 0;
                lnkUpdate.Visible = UID == UserId && ((StatusId & (PNRRequireStatus.PENDDING| PNRRequireStatus.CANCELD| PNRRequireStatus.ERROR)) != 0) && (bool)ViewState["Approve"];

                BaseRegisterStartupScript<UpdatePanel>(GetUpdatePanel(@"pnlContent") as UpdatePanel, lnkUpdate.ClientID, string.Format(@"$('#{0}').linkbutton({{   
    iconCls: 'icon-clock_red'  
}});  
", lnkUpdate.ClientID), true);

                BaseRegisterStartupScript<UpdatePanel>(GetUpdatePanel(@"pnlContent") as UpdatePanel, lnkHistory.ClientID, string.Format(@"$('#{0}').linkbutton({{   
    iconCls: 'icon-application_view_tile'  
}});  
", lnkHistory.ClientID), true);

                BaseRegisterStartupScript<UpdatePanel>(GetUpdatePanel(@"pnlContent") as UpdatePanel, lnkCancel.ClientID, string.Format(@"$('#{0}').linkbutton({{   
    iconCls: 'icon-control_pause_blue'  
}});  
", lnkCancel.ClientID), true);


                BaseRegisterStartupScript<UpdatePanel>(GetUpdatePanel(@"pnlContent") as UpdatePanel, lnkApprove.ClientID, string.Format(@"$('#{0}').linkbutton({{   
    iconCls: 'icon-flag_green'  
}});  
", lnkApprove.ClientID), true);


                //lnkPnrDesription.Visible = !string.IsNullOrEmpty(result);
                lnkHistory.OnClientClick = string.Format(@"$.jBox.messager('{0}', '指令信息', 0, {{width:650, showType: 'slide',icon:'warning',timeout: 10000 }});return false;", result);

                lnkCancel.OnClientClick = string.Format(@"javascript: $.jBox.confirm(""确实需要取消此订座需求？"", ""取消提示"", function(v,h,f){{ if(v){{ $.post('../ISAPI/SysUserAPI.ashx',{{Action:'CancelRequire',ID:'{0}' }},function(){{ $.jBox.tip('取消成功', 'success'); }}); }}  return true;  }}, {{bottomText:'取消请求后系统不再自动提示用户', buttons: {{ '确定': true, '取消': false}} }}); return false;", Id, lnkCancel.ClientID);

                lnkApprove.OnClientClick = string.Format(@"javascript: $.jBox.confirm(""确实需要批准此订座需求？"", ""审核提示"", function(v,h,f){{ if(v==3)return true;  $.post('../ISAPI/SysUserAPI.ashx',{{Action:(v==1?'ApproveRequire':(v==2?'RejectRequire':'')),ID:'{0}' }},function(){{ $.jBox.tip('审核完成', 'success'); }});  return true;  }}, {{bottomText:'审核成功后系统将自动轮寻航班情况', buttons: {{ '通过': 1, '拒绝': 2,'取消':'3'}} }}); return false;", Id, lnkCancel.ClientID);

            }

        }


        /// <summary>
        /// 初始化EasyUI控件CSS
        /// </summary>
        protected override void InitEasyUI()
        {
            BaseRegisterStartupScript<UpdatePanel>(GetUpdatePanel(@"pnlContent") as UpdatePanel, btnQuery.ClientID, string.Format(@"$('#{0}').linkbutton({{   
    iconCls: 'icon-search'  
}});  
", btnQuery.ClientID), true);

            BaseRegisterStartupScript<UpdatePanel>(GetUpdatePanel(@"pnlContent") as UpdatePanel, dlUploader.ClientID, string.Format(@"$('#{0}').combobox();  
", dlUploader.ClientID), true);

            BaseRegisterStartupScript<UpdatePanel>(GetUpdatePanel(@"pnlContent") as UpdatePanel, tbEndDate.ClientID, string.Format(@"$('#{0}').datebox();  
", tbEndDate.ClientID), true);

            BaseRegisterStartupScript<UpdatePanel>(GetUpdatePanel(@"pnlContent") as UpdatePanel, tbStartDate.ClientID, string.Format(@"$('#{0}').datebox();  
", tbStartDate.ClientID), true);

            BaseRegisterStartupScript<UpdatePanel>(GetUpdatePanel(@"pnlContent") as UpdatePanel, tbStartDate.ClientID, string.Format(@"$('#{0}').datebox();  
", tbStartDate.ClientID), true);

        }

    }
}
